package com.chenjiahao.kaiyanwan.ui.discovery

import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chenjiahao.kaiyanwan.R
import com.chenjiahao.kaiyanwan.base.BaseFragment
import com.chenjiahao.kaiyanwan.logic.exception.ExceptionHandle
import com.chenjiahao.kaiyanwan.logic.util.DisplayManager
import kotlinx.android.synthetic.main.fragment_category.*
import java.lang.Exception

/**
 * Created by chenjh on 2020/9/17
 */
class CategoryFragment : BaseFragment() {
    private var mTitle: String? = null

    private val viewModel by lazy { ViewModelProvider(this).get(DiscoveryViewModel::class.java) }
    private val mCategoryAdapter by lazy { activity?.let { CategoryAdapter(it,viewModel.mCategoryList,R.layout.item_category) } }

    companion object {
        fun getInstance(title: String): CategoryFragment {
            val fragment = CategoryFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_category

    override fun initView() {
        mLayoutStatusView = multipleStatusView
        mRecyclerView.adapter = mCategoryAdapter
        mRecyclerView.layoutManager = GridLayoutManager(activity,2)
        mRecyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                val position = parent.getChildPosition(view)
                val offset =2

                outRect.set(if (position % 2 == 0) 0 else offset, offset,
                    if (position % 2 == 0) offset else 0, offset)
            }

        })

    }

    override fun lazyLoad() {
        viewModel.requestCategory()
        viewModel.getCategoryInfo.observe(this, Observer {
            val categoryData=it.getOrNull()
            if(categoryData!=null){
                viewModel.mCategoryList=categoryData
                mCategoryAdapter?.setData(viewModel.mCategoryList)

            }else{
                showError(ExceptionHandle.handleException(it.exceptionOrNull() as Exception), ExceptionHandle.errorCode)
            }
        })
    }
}